﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;

using System.Drawing;

/// <summary>
/// CommonClass 的摘要说明
/// </summary>
public class CommonClass
{
    public CommonClass()
    {

    }

    /// <summary>
    /// 加密数据
    /// </summary>
    /// <param name="password">明文</param>
    /// <param name="format">算法:sha1,md5</param>
    /// <returns></returns>
    public static string Encryption(string password, string format)
    {
        password = password.Trim();
        return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, format).Trim();
    }
    /// <summary>
    /// 弹出信息
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    public static void Alert(string msg)
    {
        HttpContext.Current.Response.Write("<script>alert('" + msg + "');</script>");
    }
    /// <summary>
    /// 弹出信息并转向url
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="url"></param>
    public static void Alert(string msg,string url)
    {
        HttpContext.Current.Response.Write("<script>alert('" + msg + "');location.href='" + url + "';</script>");
    }

    /// <summary>
    /// 弹出确认信息
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    public static void Confirm(string msg)
    {
        HttpContext.Current.Response.Write("<script>return confirm('" + msg + "');</script>");
    }
    /// <summary>
    /// 关闭窗口
    /// </summary>
    public static void WindowClose()
    {
        HttpContext.Current.Response.Write("<sc" + "ript>window.close();</sc" + "ript>");
    }
    /// <summary>
    /// 打开新窗口
    /// </summary>
    /// <param name="url">路径</param>
    public static void Open(string url)
    {
        HttpContext.Current.Response.Write("<script>window.open('" + url + "');</script>");
    }
    /// <summary>
    /// 转到其它URL
    /// </summary>
    /// <param name="url">路径</param>
    public static void Redirect(string url)
    {
        HttpContext.Current.Response.Write("<script>location.href='" + url + "';</script>");
    }
    /// <summary>
    /// 去登陆
    /// </summary>
    public static void ToLogin()
    {
        HttpContext.Current.Response.Write("<script>location.href='/default.aspx';</script>");
    }
    /// <summary>
    /// 转到其它URL
    /// </summary>
    /// <param name="url">路径</param>
    public static void Redirect(string url,bool top)
    {
        if (top)
        {
            HttpContext.Current.Response.Write("<script>top.location.href='" + url + "';</script>");
        }
        else
        {
            HttpContext.Current.Response.Write("<script>location.href='" + url + "';</script>");
        }
    }
    /// <summary>
    /// 显示错误信息并弹出信息
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string Error(string s)
    {
        return "<font color='red'>" + s + "</font><script>alert('" + s  + "');</script>";
    }
    /// <summary>
    /// 显示弹出信息
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string ShowMsg(string s)
    {
        return "<font color='red'>" + s + "</font><script>alert('" + s + "');</script>";
    }
    /// <summary>
    /// 通过key取得配置文件中的value值
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetConfigurationSetting(string key)
    {
        return System.Configuration.ConfigurationSettings.AppSettings[key];
    }
    /// <summary>
    /// 给DataGrid删除按钮添加客户端验证
    /// </summary>
    /// <param name="dg">DataGrid</param>
    /// <param name="del">删除按钮名称</param>
    public static void ItemDataBount(System.Web.UI.WebControls.DataGrid dg, string del)
    {
        for (int i = 0; i < dg.Items.Count; i++)
        {
            System.Web.UI.WebControls.LinkButton lbtn = (System.Web.UI.WebControls.LinkButton)dg.Items[i].FindControl(del);

            if (lbtn != null)
            {
                lbtn.Attributes.Add("onclick", "javascript:return confirm('确定删除此项吗？');");
            }
        }
    }

    /// <summary>
    /// 给GridView删除按钮添加客户端验证
    /// </summary>
    /// <param name="dg">GridView</param>
    /// <param name="del">删除按钮名称</param>
    public static void ItemDataBount(System.Web.UI.WebControls.GridView gv, string del)
    {
        for (int i = 0; i < gv.Rows.Count; i++)
        {
            System.Web.UI.WebControls.LinkButton lbtn = (System.Web.UI.WebControls.LinkButton)gv.Rows[i].FindControl(del);

            if (lbtn != null)
            {
                lbtn.Attributes.Add("onclick", "javascript:return confirm('确定删除此项吗？');");
            }
        }
    }
    /// <summary>
    ///当前记录的行KeyID
    /// </summary>
    /// <param name="gv"></param>
    /// <param name="rowIndex"></param>
    /// <returns></returns>
    public static int GetCuurentID(System.Web.UI.WebControls.GridView gv, int rowIndex)
    {
        return Convert.ToInt32(gv.DataKeys[rowIndex].Value);
    }
    /// <summary>
    ///通过URL下载网页HTML,返回HTML代码
    /// </summary>
    /// <param name="url">要下载的网页的路径</param>
    /// <returns></returns>
    public static string GetStrByUrl(string url)
    {
        try
        {
            string source = "";
            WebClient client = new WebClient();
            Stream sr = client.OpenRead(url);
            if (sr != null)
            {
                StreamReader streamr = new StreamReader(sr, Encoding.Default);
                source = streamr.ReadToEnd();
                sr.Close();
                streamr.Close();
            }
            return source.Replace("\n", "").Replace("\t", "").Replace("\r", "");
        }
        catch (System.InvalidOperationException ex)
        {
            return "";
            throw ex;
        }
    }
    /// <summary>
    /// 读取文件
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <returns></returns>
    public static string ReadFileToString(string path)
    {
        StreamReader sr = new StreamReader(path);
        if (sr != null)
        {
            string s = sr.ReadToEnd();
            sr.Close();
            return s;
        }
        else
        {
            return "";
        }
    }
    /// <summary>
    /// 把字符存储为文件
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <param name="content">内容</param>
    public static void SaveToFile(string path, string content)
    {
        StreamWriter sw = new StreamWriter(path, false, System.Text.Encoding.Default);
        sw.Write(content);
        sw.Close();
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="url">文件所在网络上的地址</param>
    /// <param name="filepath">保存在本地的地址</param>
    public static void DownFileByUrl(string url, string filepath)
    {
        WebClient client = new WebClient();
        client.DownloadFile(url, filepath);
    }

    /// <summary>
    /// DataGrid全选,全不选;用法:CommonClass.BoundCheck(dg,"chk","chkall",out str,out function);
    /// if(!Page.IsClientScriptBlockRegistered(function)){Page.RegisterClientScriptBlock(function,str);}
    /// </summary>
    /// <param name="dg">datagrid 控件</param>
    /// <param name="chk"></param>
    /// <param name="dgchkall">全选控件</param>
    /// <param name="regScript"></param>
    /// <param name="function"></param>
    public static void BoundCheckBox(System.Web.UI.WebControls.DataGrid dg, string chk, string dgchkall, out string regScript, out string function)
    {
        regScript = "";
        System.Text.StringBuilder strScript = new System.Text.StringBuilder();
        if (dg.Controls.Count > 0)
        {
            foreach (DataGridItem item in dg.Controls[0].Controls)
            {
                if (item.ItemType == ListItemType.Header)
                {
                    CheckBox chkAll = (CheckBox)item.FindControl(dgchkall);
                    if (chkAll != null)
                    {
                        strScript = new System.Text.StringBuilder("<script language='javascript'> \n");
                        strScript.Append("    function checkStatus() { \n");
                        strScript.Append("        var bAll = true; \n");
                        strScript.Append("        bAll = document.all('" + chkAll.ClientID + "').checked; \n");

                        for (int i = 0; i < dg.Items.Count; i++)
                        {
                            CheckBox chk1 = (CheckBox)dg.Items[i].FindControl(chk);
                            if (chk1 != null)
                            {
                                strScript.Append("        document.all('" + dg.Items[i].FindControl(chk).ClientID + "').checked = bAll; \n");
                            }
                        }
                        strScript.Append("    } \n");
                        strScript.Append("</script> \n");

                        chkAll.Attributes.Add("onclick", "checkStatus()");
                    }
                }
            }
        }
        function = "checkStatus";
        regScript = strScript.ToString();
    }
    /// <summary>
    /// GridView全选,全不选;用法:CommonClass.BoundCheck(gv,"chk","chkall",out str,out function);//在PreRender事件下调用后再用下面的代码
    /// if(!Page.IsClientScriptBlockRegistered(function)){Page.RegisterClientScriptBlock(function,str);}
    /// </summary>
    /// <param name="dg">datagrid 控件</param>
    /// <param name="chk"></param>
    /// <param name="dgchkall">全选控件</param>
    /// <param name="regScript"></param>
    /// <param name="function"></param>
    public static void BoundCheckBox(System.Web.UI.WebControls.GridView gv, string chk, string chkall, out string regScript, out string function)
    {
        regScript = "";
        System.Text.StringBuilder strScript = new System.Text.StringBuilder();
        if (gv.Controls.Count > 0)
        {

            CheckBox gvchkall = (CheckBox)(gv.HeaderRow.FindControl(chkall));
            if (gvchkall != null)
            {

                strScript = new System.Text.StringBuilder("<script language='javascript'> \n");
                strScript.Append("    function checkStatus() { \n");
                strScript.Append("        var bAll = true; \n");
                strScript.Append("        bAll = document.all('" + gvchkall.ClientID + "').checked; \n");

                for (int i = 0; i < gv.Rows.Count; i++)
                {
                    CheckBox chk1 = (CheckBox)gv.Rows[i].FindControl(chk);
                    if (chk1 != null)
                    {
                        strScript.Append("        document.all('" + gv.Rows[i].FindControl(chk).ClientID + "').checked = bAll; \n");
                    }
                }
                strScript.Append("    } \n");
                strScript.Append("</script> \n");

                gvchkall.Attributes.Add("onclick", "checkStatus()");
            }
        }
        function = "checkStatus";
        regScript = strScript.ToString();
    }

    /// <summary>
    /// 当前时间作为文件名称
    /// </summary>
    /// <returns></returns>
    public static string GetFileName()
    {
        return System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();
    }


    /// <summary>
    /// 分页代码
    /// </summary>
    /// <param name="total">记录数</param>
    /// <param name="pagesize">每页显示记录数</param>
    /// <param name="webname">网页名称:有其它get参数时后面加"&",没有时加"?"</param>
    /// <param name="index">当前页</param>
    /// <param name="barnum">页码数量</param>
    /// <returns></returns>
    public static string PageBar(int total, int pagesize, string webname, int index, int barnum)
    {
        string pagebar = " ";
        int re = 0;
        int pages = Math.DivRem(total, pagesize, out re);
        if (re > 0)
        {
            pages = pages + 1;
        }

        string first = " <a href=\"" + webname + "\">首页</a>&nbsp; ";
        string last = "&nbsp;&nbsp;<a href=\"" + webname + "index=" + pages.ToString() + "\">尾页</a>";
        int sep = barnum / 2;
        //上一页,下一页
        int prepage = index - 1;
        int nextpage = index + 1;
        string strprepage = "";
        string strnextpage = "";
        if (prepage > 0)
        {
            //上一页
            strprepage = "<a href=\"" + webname + "index=" + prepage.ToString() + "\"> [上一页]</a>&nbsp; \n";
        }

        if (nextpage < pages + 1)
        {
            //下一页
            strnextpage = "<a href=\"" + webname + "index=" + nextpage.ToString() + "\"> [下一页]</a> &nbsp;\n";
        }

        if (pages < barnum)
        {
            for (int i = 1; i < pages + 1; i++)
            {
                if (i != index)
                {
                    pagebar += "<a href=\"" + webname + "index=" + i.ToString() + "\"> [" + i.ToString() + "]</a> &nbsp;  \n";
                }
                else
                {
                    pagebar += "&nbsp;[" + i.ToString() + "]&nbsp;\n";
                }
            }
            //当页码数量小于barnum时不显示首页和尾页
            first = "";
            last = "";
        }
        else
        {
            int pre1 = index - sep;//前sep页
            if (pre1 < 1)
            {
                pre1 = 1;
            }
            int next1 = index + sep; ;//后sep页
            if (next1 > pages)
            {
                next1 = pages;
            }

            for (int i = pre1; i < next1 + 1; i++)
            {
                if (i != index)
                {
                    pagebar += "<a href=\"" + webname + "index=" + i.ToString() + "\"> [" + i.ToString() + "]</a> &nbsp; \n";
                }
                else
                {
                    pagebar += "&nbsp;[" + i.ToString() + "]&nbsp;\n";
                }
            }

        }
        pagebar = first + strprepage + pagebar + strnextpage + last;
        return pagebar;
    }


    /// <summary>
    /// 分页代码
    /// </summary>
    /// <param name="total">记录数</param>
    /// <param name="pagesize">每页显示记录数</param>
    /// <param name="webname">网页名称:有其它get参数时后面加"&",没有时加"?"</param>
    /// <param name="index">当前页</param>
    /// <param name="barnum">页码数量</param>
    /// <returns></returns>
    public static string PageBar(int total, int pagesize, string webname, int index, int barnum,string extend)
    {
        string pagebar = " ";
        int re = 0;
        int pages = Math.DivRem(total, pagesize, out re);
        if (re > 0)
        {
            pages = pages + 1;
        }

        string first = " <a href=\"" + webname + "\">首页</a>&nbsp; ";
        string last = "&nbsp;&nbsp;<a href=\"" + webname + "_" + pages.ToString()+extend  + "\">尾页</a>";
        int sep = barnum / 2;
        //上一页,下一页
        int prepage = index - 1;
        int nextpage = index + 1;
        string strprepage = "";
        string strnextpage = "";
        if (prepage > 0)
        {
            //上一页
            strprepage = "<a href=\"" + webname + "_" + prepage.ToString() + extend + "\"> [上一页]</a>&nbsp; \n";
        }

        if (nextpage < pages + 1)
        {
            //下一页
            strnextpage = "<a href=\"" + webname + "_" + nextpage.ToString() + extend + "\"> [下一页]</a> &nbsp;\n";
        }

        if (pages < barnum)
        {
            for (int i = 1; i < pages + 1; i++)
            {
                if (i != index)
                {
                    pagebar += "<a href=\"" + webname + "_" + i.ToString() + extend + "\"> [" + i.ToString() + "]</a> &nbsp;  \n";
                }
                else
                {
                    pagebar += "&nbsp;[" + i.ToString() + "]&nbsp;\n";
                }
            }
            //当页码数量小于barnum时不显示首页和尾页
            first = "";
            last = "";
        }
        else
        {
            int pre1 = index - sep;//前sep页
            if (pre1 < 1)
            {
                pre1 = 1;
            }
            int next1 = index + sep; ;//后sep页
            if (next1 > pages)
            {
                next1 = pages;
            }

            for (int i = pre1; i < next1 + 1; i++)
            {
                if (i != index)
                {
                    pagebar += "<a href=\"" + webname + "_" + i.ToString() + extend + "\"> [" + i.ToString() + "]</a> &nbsp; \n";
                }
                else
                {
                    pagebar += "&nbsp;[" + i.ToString() + "]&nbsp;\n";
                }
            }

        }
        pagebar = first + strprepage + pagebar + strnextpage + last;
        return pagebar;
    }
    /// <summary>
    /// 去掉字符串中的HTML
    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static string RepalceHTML(string source)
    {
        source = Regex.Replace(source, "<(\\s|\\S)+?>", "", RegexOptions.IgnoreCase);
        return source;
    }

    public void DropdowListBound(System.Web.UI.WebControls.DropDownList ddl, System.Data.DataView dv, string valueField, string textField)
    {
        ddl.DataSource = dv;
        ddl.DataValueField = valueField;
        ddl.DataTextField = textField;
        ddl.DataBind();
    }
    public void DataBound(System.Web.UI.WebControls.DataGrid dg, System.Data.DataView dv)
    {
        dg.DataSource = dv;
        dg.DataBind();
    }
    public void DataBound(System.Web.UI.WebControls.Repeater rpt, System.Data.DataView dv)
    {
        rpt.DataSource = dv;
        rpt.DataBind();
    }
    public void DataBound(System.Web.UI.WebControls.DataList dl, System.Data.DataView dv)
    {
        dl.DataSource = dv;
        dl.DataBind();
    }
    public static string ServerFile(string strpath)
    {
        return System.Web.HttpContext.Current.Server.MapPath(strpath);
    }
    public static string HtmlDeCode(string str)
    {
        return System.Web.HttpContext.Current.Server.HtmlDecode(str);
    }
    public static string HtmlEnCode(string str)
    {
        return System.Web.HttpContext.Current.Server.HtmlEncode(str);
    }
    public static string UrlDeCode(string str)
    {
        return System.Web.HttpContext.Current.Server.UrlDecode(str);
    }
    public static string UrlEnCode(string str)
    {
        return System.Web.HttpContext.Current.Server.UrlEncode(str);
    }
    /// <summary>
    /// 返回数字的汉字
    /// </summary>
    /// <param name="inti"></param>
    /// <returns></returns>
    public static  string GetHan(int inti)
    {
        string[] c ={ "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", };
        for (int i = 0; i < c.Length; i++)
        {
            if (inti == i + 1)
            {
                return c[i];
            }
        }
        return inti.ToString();
    }
    public static void CreateCookie(string cookiename)
    {
        HttpCookie cook = new HttpCookie(cookiename);
        cook["hits"] = "00";
        cook.Expires = DateTime.Now.AddDays (1);
        HttpContext.Current.Response.Cookies.Add(cook);
    }
    /// <summary>
    /// 替换掉不要的内容
    /// </summary>
    /// <param name="input"></param>
    /// <param name="reg">正则表达式</param>
    /// <returns></returns>
    public static  string ClearByRegex(string input, string reg)
    {
        return Regex.Replace(input, reg, "", RegexOptions.IgnoreCase);
    }
    /// <summary>
    /// 返回整型查询字符串的值,异常返回0
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static int GetIntQueryString(string name)
    {
        if (HttpContext.Current.Request.QueryString[name] != null)
        {
            try
            {
                return Convert.ToInt32(HttpContext.Current.Request.QueryString[name]);
            }
            catch
            {
                return 0;
            }
        }
        else
        {
            return 0;
        }
    }
    /// <summary>
    /// 返回页码,小于1则返回1
    /// </summary>
    /// <returns></returns>
    public static int GetIndex()
    {
        try
        {
            int index= Convert.ToInt32(HttpContext.Current.Request.QueryString["index"]);
            if (index < 1)
            {
                return 1;
            }
            return index;
        }
        catch
        {
            return 1;
        }
    }
}
